<template>
  <div class="app-container">
    <el-row>
      <!--区域数据-->
      <el-col :xs="24" v-show="treeVisibale === true" class="tree_bg">
        <!-- <div>
          <el-input v-model="keyWordName" placeholder="输入关键字进行过滤" clearable size="small" prefix-icon="el-icon-search"
            style="margin-bottom: 20px" />
        </div> -->
        <div class="head-container">
          <el-tree :data="areaOptions"
                   :props="defaultProps"
                   :expand-on-click-node="false"
                   :filter-node-method="filterNode"
                   ref="tree"
                   node-key="id"
                   default-expand-all
                   highlight-current
                   v-loading="treeloading"
                   show-checkbox
          />
        </div>
        <div class="tree_close" @click="changeTreeShow">
          <i class="el-icon-caret-left" style="color: white"></i>
        </div>
      </el-col>
      <el-col class="jiange"></el-col>
      <div class="tree_open" @click="changeTreeShow" v-show="treeVisibale === false">
        <i class="el-icon-caret-right" style="color: white"></i>
      </div>
      <!--大用户表历史数据-->
      <el-col :xs="24" :class="treeVisibale ? 'table_small_bg' : 'table_big_bg'">
        <el-row class="line-bottom" v-show="showSearch">
          <el-col class="form_col">
            <el-form :model="queryParams" ref="queryForm" :size="size" :label-width="labelWidth">
              <div id="searchFilter" :gutter="10" style="display: flex; flex-wrap: wrap">
                <el-form-item label="用户编号" prop="userId">
                  <el-input v-model="queryParams.userId" placeholder="输入用户编号" clearable size="small"></el-input>
                </el-form-item>
                <el-form-item label="楼栋名称" prop="ldName">
                  <el-input v-model="queryParams.ldName" placeholder="输入楼栋名称" clearable size="small"></el-input>
                </el-form-item>
                <el-form-item label="设备编号" prop="TerminalID">
                  <el-input v-model="queryParams.TerminalID" placeholder="输入设备编号" clearable
                            size="small"></el-input>
                </el-form-item>
                <el-form-item label="冻结时间" prop="params">
                  <el-date-picker v-model="timevalue" type="daterange" value-format="yyyy-MM-dd" range-separator="至"
                                  start-placeholder="开始日期"
                                  end-placeholder="结束日期" style="width: 120%;">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="通讯地址" prop="communicateAddress">
                  <el-input v-model="queryParams.communicateAddress" placeholder="输入通讯地址" clearable
                            size="small"></el-input>
                </el-form-item>
                <el-form-item style="width: 0px;"></el-form-item>
              </div>
            </el-form>
          </el-col>
          <el-col class="form_query">
            <el-button v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text">
              <span>
                {{ fold ? '收起筛选' : '更多筛选' }}
              </span>
            </el-button>
            <el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
            <el-button @click="resetQuery" size="mini">重置</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="mb8 padding_top_bottom">
          <RightDropdown :columns="columns" :showSearch.sync="showSearch" @queryTable="getList"
                         @export="handleExport"></RightDropdown>
        </el-row>
        <el-row>
          <el-table v-loading="loading" :data="dataList" max-height="600" ref="table">
            <el-table-column v-for="item in columns" :key="item.key" :prop="item.dataindex" align="center"
                             :show-overflow-tooltip="true" :label="item.label" v-if="item.visible">
            </el-table-column>
          </el-table>
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {getDosageList} from "@/api/datastatistics/meterread/daymonthdosage.js"
import {getAreasList} from '@/api/basedata/areas'
import moment from 'moment'

export default {
  name: "DayDosage",
  data() {
    return {
      // 列信息
      columns: [
        // { key: 0, label: `平台主键`, visible: false, dataindex:'ReadGrowthRate' },
        {key: 0, label: `楼栋名称`, visible: true, dataindex: 'ldName'},
        {key: 1, label: `用户编号`, visible: true, dataindex: 'userId'},
        {key: 2, label: `用户名称`, visible: true, dataindex: 'userName'},
        {key: 3, label: `门牌号`, visible: true, dataindex: 'roomName'},
        {key: 4, label: `设备编号`, visible: true, dataindex: 'TerminalID'},
        {key: 5, label: `通讯地址`, visible: true, dataindex: 'communicateAddress'},
        {key: 6, label: `冻结日期`, visible: true, dataindex: 'freezeTime'},
        {key: 7, label: `冻结读数(m³)`, visible: true, dataindex: 'endReading'},
        {key: 8, label: `日用量(m³)`, visible: true, dataindex: 'cumulativeFlow'},
        // { key: 9, label: `实时时间`, visible: true, dataindex:'frozenType' },
      ],
      size: 'small',
      collapseAble: false,
      fold: false,
      maxShow: '4',
      labelWidth: '90px',
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 表格数据
      dataList: [],
      // 区域树选项
      areaOptions: [],
      // 区域名称
      keyWordName: undefined,
      // 树状态
      treeVisibale: true,
      // 遮罩层
      treeloading: true,
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        frozenType: 'day',
        areaCode: [],
        beginTime: moment(new Date().getTime() - 3600 * 1000 * 24 * 30).format('YYYY-MM-DD'),
        endTime: moment(new Date()).format('YYYY-MM-DD'),
        userId: null,
        ldName: null,
        TerminalID: null,
        communicateAddress: null,
      },
      // 总条数
      total: 0,
      showtime: true,
      // 冻结日期
      timevalue: [moment(new Date().getTime() - 3600 * 1000 * 24 * 30).format('YYYY-MM-DD'), moment(new Date()).format('YYYY-MM-DD')],
    };
  },
  created() {
    this.tip()
    this.getAreaTree()
  },
  mounted() {
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }
  },
  watch: {
    // 根据名称筛选区域树
    keyWordName(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    init() {
      // 调用接口获取到数据后
      let _self = this
      this.$nextTick(() => {
        window.setTimeout(() => {
          _self.$refs.table.doLayout()
        }, 100)
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      let choiseCheckList = this.$refs.tree.getCheckedNodes();
      let newchoiseCheckList = []
      if (choiseCheckList.length > 0) {
        choiseCheckList.forEach((item) => {
          newchoiseCheckList.push(item.areaCode)
        })
        this.queryParams.areaCode = newchoiseCheckList
        if (this.timevalue.length > 0) {
          this.queryParams.beginTime = this.timevalue[0]
          this.queryParams.endTime = this.timevalue[1]
        }
        this.getList()
      } else if (choiseCheckList.length === 0) {
        this.$modal.msgWarning("至少选择一个区域!")
      }
    },
    // 重置表单
    resetQuery() {
      // this.$nextTick(() => {
      //   this.$refs.tree.setCheckedNodes([]);
      // })
      this.$refs.tree.setCheckedNodes([]);
      this.timevalue = [moment(new Date().getTime() - 3600 * 1000 * 24 * 30).format('YYYY-MM-DD'), moment(new Date()).format('YYYY-MM-DD')],
        this.queryParams = {
          pageNum: 1,
          pageSize: 20,
          frozenType: 'day',
          areaCode: this.$refs.tree.getCheckedNodes(),
          beginTime: moment(new Date().getTime() - 3600 * 1000 * 24 * 30),
          endTime: moment(new Date()).format('YYYY-MM-DD'),
          userId: null,
          ldName: null,
          TerminalID: null,
          communicateAddress: null,
        }
      this.dataList = []
      this.handleQuery()
    },
    // 获取表格数据
    getList() {
      this.loading = true;
      getDosageList(this.queryParams).then(response => {
        if (response.code === 200) {
          this.dataList = response.rows
          this.init()
          this.loading = false;
          this.total = response.total
        } else {
          this.$modal.msgError("数据查看失败!")
          this.loading = false;
        }
      });
    },
    // 页面提示信息
    tip() {
      this.$modal.msgWarning("请选择一个区域查看数据!")
      this.loading = false;
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.size}`)
      const len = group?.length ? group?.length - 1 : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    /** 查询区域下拉树结构 */
    getAreaTree() {
      // getAreasList().then(response => {

      // });
      this.treeloading = true
      let list_ = JSON.parse(localStorage.getItem('list'))
      list_.forEach((item) => {
        var obj = {
          id: item.areaCode,
          areaCode: item.areaCode,
          label: item.areaName,
          children: item.children && item.children.length > 0 ? this.copyTree(item.children) : item.children
        }
        this.areaOptions.push(obj)
      })
      this.treeloading = false
    },
    copyTree(list) {
      list.forEach((item) => {
        item.id = item.areaCode;
        item.label = item.areaName;
        item.children = item.children;
        if (item.children && item.children.length) {
          this.copyTree(item.children);
        }
      });
      return list;
    },
    // 改变tree的显示与隐藏
    changeTreeShow() {
      this.treeVisibale = !this.treeVisibale
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('datastatistics/terminalXbStatisticAnalysis/exportDayOrMonth', {
        ...this.queryParams,
      }, `户表日用量统计_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss" scoped>
.form_col {
  width: 80%;

  ::v-deep .el-form {
    width: 100%;
  }

  ::v-deep .el-form-item {
    width: 25%;
  }
}

.form_query {
  width: 20%;
  text-align: right;
}
</style>
